package com.mall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.exception.BizIllegalException;
import com.mall.common.utils.BeanUtils;
import com.mall.common.utils.CollUtils;
import com.mall.common.utils.UserContext;
import com.mall.domain.dto.CartFormDTO;
import com.mall.domain.dto.ItemDTO;
import com.mall.domain.po.Cart;
import com.mall.domain.vo.CartVO;
import com.mall.mapper.CartMapper;
import com.mall.service.CartService;
import com.mall.service.ItemService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService{
    @Resource
    private CartMapper cartMapper;
    @Resource
    private ItemService itemService;

    @Override
    public void addItemToCart(CartFormDTO cartFormDTO) {
        Long userId = UserContext.getUser();

        // 检查购物车已存在该商品
        if (exist(cartFormDTO.getItemId(),userId)){
            // 存在，购物车中的该商品数量+1
            cartMapper.updateItemCount(cartFormDTO.getItemId(),userId);
            return;
        }

        // 不存在，检查是否超过购物车上限
        checkCartsFull(userId);

        // 新增
        Cart cart = BeanUtils.copyProperties(cartFormDTO, Cart.class);
        cart.setUserId(userId);
        this.save(cart);
    }

    @Override
    public List<CartVO> queryMyCarts() {
        // 1.查询我的购物车列表
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        Long userId = UserContext.getUser();
        cartQueryWrapper
                .eq("user_id",userId);
        List<Cart> carts = this.list(cartQueryWrapper);
        if (CollUtils.isEmpty(carts)) {
            return CollUtils.emptyList();
        }

        // 2.转换VO
        List<CartVO> vos = BeanUtils.copyList(carts, CartVO.class);

        // 3.处理VO中的商品信息
        handleCartItems(vos);

        // 4.返回
        return vos;
    }

    @Override
    public void removeByItemIds(Collection<Long> ids) {
        // 1.构建删除条件，userId和itemId
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
        queryWrapper.lambda()
                .eq(Cart::getUserId, UserContext.getUser())
                .in(Cart::getItemId, ids);
        // 2.删除
        remove(queryWrapper);
    }

    private void handleCartItems(List<CartVO> vos) {
        // 1.获取商品id
        Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
        // 2.查询商品
        List<ItemDTO> items = itemService.getItemByIds(itemIds);
        if (CollUtils.isEmpty(items)) {
            return;
        }
        // 3.转为 id 到 item的map
        Map<Long, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity()));
        // 4.写入vo
        for (CartVO v : vos) {
            ItemDTO item = itemMap.get(v.getItemId());
            if (item == null) {
                continue;
            }
            v.setNewPrice(item.getPrice());
            v.setStatus(item.getStatus());
            v.setStock(item.getStock());
        }
    }

    // 商品是否存在
    private boolean exist(Long itemId, Long userId) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper
                .eq("user_id",userId)
                .eq("item_id",itemId);
        long count = this.count(cartQueryWrapper);
        return count > 0;
    }

    // 检查是否超过购物车上限（10）
    private void checkCartsFull(Long userId) {
        long count = lambdaQuery().eq(Cart::getUserId, userId).count();
        if (count >= 10) {
            throw new BizIllegalException(StrUtil.format("用户购物车课程不能超过{}", 10));
        }
    }


}
